import socket


def send_file_2_client(new_client_socket, client_addr):
    # 接收客户端发过来的 要下载的文件名字
    file_name = new_client_socket.recv(1024).decode("gbk")
    print("客户端（%s）需要下载的文件是：%s" % (str(client_addr), file_name))
    file_content = None
    # 打开要发送的文件
    try:
        f = open(file_name, "rb")
        file_content = f.read()
    except Exception as e:
        print("没有要下载的文件(%s)" % file_name)
    # 发送文件数据给客户端
    if file_content:
        new_client_socket.send(file_content)


def main():
    # 创建套接字
    tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定本地信息
    tcp_server.bind(("", 8080))
    # 让默认的套接字由主动变被动
    tcp_server.listen(128)
    # 等待client连接
    while True:
        new_client_socket, client_addr = tcp_server.accept()
        send_file_2_client(new_client_socket, client_addr)
        new_client_socket.close()
    tcp_server.close()


if __name__ == "__main__":
    main()
